package pers.xukai.common.utils;

import org.springframework.lang.NonNull;
import pers.xukai.common.exception.BizException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author : 殷绪凯
 * @description : someDescription
 * @since : 2022年 12月 02日 11:30
 */
public class HttpUtil {

    /**
     * 向前端写入流文件
     * @param response
     * @param fileName
     * @param fileExt
     * @param inputStream
     * @param contentType
     */
    public static void writeStreamToResponse(@NonNull HttpServletResponse response, @NonNull String fileName, String fileExt, @NonNull InputStream inputStream,  @NonNull String contentType) {
        try (OutputStream outputStream = response.getOutputStream()) {
            response.resetBuffer();
            // 定义输出类型
            response.setContentType(contentType);
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            response.addHeader("Content-Disposition", "attachment;filename="
                    + fileName + "." + fileExt.toLowerCase());
            inputStream.transferTo(outputStream);
        } catch (IOException e) {
            throw new BizException("将inputStream数据发送到response时出现异常，信息：" + e.getMessage(), e);
        }
    }
}
